import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';

import PointsExchangeABI from "../contract/ABIs/PointsExchange.json"; // 积分兑换合约合约 ABI
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI

import PointsExchangeAddress from "../contract/ADDRESSes/PointsExchangeAddress.js" // 积分兑换合约地址
import AdminNavBar from './nav/AdminNavBar.js';
// import '../static/indexcss/aacsss.css';
import Eye from './Eye.js'
import { Table, Modal } from 'antd';
import Admin_integralNavBar from './nav/Admin_integralNavBar.js'
import gb from '../static/bootstrap/images/gb.svg';
import us from '../static/bootstrap/images/us.svg';
import user3 from '../static/bootstrap/images/user3.png';
import Head from './nav/Head.js';



const Admin_RuleList = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractPointsExchange, setcontractPointsExchange] = useState(null);
    const [contractAdmin, setcontractAdmin] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);

    const [ExchangeRecordList, setExchangeRecordList] = useState('') //查看所有用户列表
    const [userAddr, setUserAddr] = useState('');// 用户账户地址
    const [IsList, setIsList] = useState(false);//控制是否显示列表
    const [giftFilter, setgiftFilter] = useState('');//用于通过礼品查询
    const columns = [
        {
            title: '用户地址',
            dataIndex: 'user',
            key: 'user',
            render: (text) => {
                const newText = text; // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '礼品',
            dataIndex: 'gift',
            key: 'gift',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '积分规则编号',
            dataIndex: 'PointRuleId',
            key: 'PointRuleId',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '是否使用',
            dataIndex: 'used',
            key: 'used',
            render: (text) => (
                <span style={{ color: 'black' }}>{text == true ? '使用' : '未使用'}</span>
            ),
        },


    ];
    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建积分兑换合约实例
                    const pointsExchangeInstance = new web3Instance.eth.Contract(
                        PointsExchangeABI,
                        PointsExchangeAddress
                    );
                    setcontractPointsExchange(pointsExchangeInstance);

                    // 创建管理员合约实例
                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setcontractAdmin(adminInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    // 检查当前账户是否是管理员本人
                    setIsAdmin(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);


    // 查看用户兑换记录函数
    const GetUserExchangeRecords = async () => {
        if (contractPointsExchange) {
            try {
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress, "Input:", userAddr);
                // 调用合约函数
                const result = await contractPointsExchange.methods.getUserExchangeRecords(userAddr).call({ from: fromAddress });
                // alert("添加规则成功")
                setExchangeRecordList(result);
                setIsList(true);//让列表显示出来
            } catch (error) {
                console.error(error);
                alert("查询规则失败")
            }
        };
    };

    const handleFilter = async () => {
        if (contractPointsExchange) {
            try {
                const filteredActivityList = ExchangeRecordList.filter((activity) => activity.gift === giftFilter);//设置通过类别查询
                setExchangeRecordList(filteredActivityList);

                setIsList(true);
            } catch (error) {
                console.error(error);
            }
        }
    };

    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}

            {/* 管理员界面 */}
            {isAdmin && (
                <div className="page-wrapper">
                    <div className="main-container" style={{
                        backgroundColor: '#FFFFFF'
                    }}>
                        <AdminNavBar address={address}></AdminNavBar>

                        <div className="app-container">
                            <Head></Head>

                            <div className="app-body">
                                <div className="container-fluid">

                                    <div>
                                        <main className="page hire-me-page">
                                            <section className="portfolio-block hire-me">
                                                <div className="foreground-component">
                                                    <div className="container">
                                                        <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                                            data-bs-theme="light"
                                                            style={{
                                                                backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                                            }}
                                                        >

                                                            <h2>用户兑换记录</h2>
                                                            <div class="mb-3">
                                                                <div className="d-flex justify-content-end mt-3">
                                                                    <div className="input-group mb-3" style={{ maxWidth: '300px' }}>
                                                                        <input
                                                                            type="text"
                                                                            className="form-control"
                                                                            placeholder="输入礼品查询"
                                                                            aria-label="礼品查询"
                                                                            aria-describedby="basic-addon2"
                                                                            value={giftFilter}
                                                                            onChange={(e) => setgiftFilter(e.target.value)}
                                                                        />
                                                                        <div className="input-group-append">
                                                                            <button className="btn btn-primary btn-lg d-block w-100" type="button" onClick={handleFilter}>查询</button>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div className="mb-3">
                                                                    <label className="form-label">用户账户地址</label>
                                                                    <input className="form-control item" type="text" placeholder="用户账户地址" value={userAddr} onChange={(e) => setUserAddr(e.target.value)} />
                                                                </div>
                                                                {IsList ? (
                                                                    <Table
                                                                        dataSource={ExchangeRecordList}
                                                                        columns={columns} // 确保你已经定义了columns
                                                                        pagination={{
                                                                            pageSize: 2,
                                                                            showTotal: false, // 隐藏总页数
                                                                            showSizeChanger: false, // 隐藏页面大小选择器
                                                                            itemRender: (current, type, originalElement) => (
                                                                                <span style={{ color: 'black' }}>
                                                                                    {current}
                                                                                </span>
                                                                            ),
                                                                        }}                                                //  onRow={onRow} // 确保你传递了onRow函数，用于保存对应的id
                                                                    />
                                                                ) : (
                                                                    <div>No activity information available.</div>
                                                                )}


                                                                <div className="mb-3 mt-4">
                                                                    <button className="btn btn-primary btn-lg d-block w-100" onClick={GetUserExchangeRecords}>查询</button>
                                                                </div>

                                                            </div>


                                                        </div>
                                                    </div>
                                                </div>
                                            </section>
                                        </main>
                                    </div>


                                </div>
                            </div>
                            <div className="app-footer">
                                <span>
                                    © Bootstrap Gallery 2023
                                </span>
                            </div>
                        </div>
                    </div>

                </div>
            )}
        </div >
    );
}

export default Admin_RuleList;